package com.chen.seckill.service.impl;

import com.chen.seckill.dao.UserMapper;
import com.chen.seckill.dao.UserPasswordMapper;
import com.chen.seckill.error.BusinessException;
import com.chen.seckill.error.EmBusinessError;
import com.chen.seckill.pojo.User;
import com.chen.seckill.pojo.UserPassword;
import com.chen.seckill.service.bo.UserBO;
import com.chen.seckill.service.UserService;
import com.chen.seckill.validator.ValidationResult;
import com.chen.seckill.validator.ValidatorImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserPasswordMapper userPasswordMapper;

    @Autowired
    private ValidatorImpl validator;

    @Override
    public UserBO getUserById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        UserPassword userPassword = userPasswordMapper.getByUserId(id);
        return convertFromUser(user, userPassword);
    }

    @Override
    @Transactional//让注册的整个过程处在一个事务中
    public void register(UserBO userBO) throws BusinessException {
        if (userBO == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        // if (StringUtils.isEmpty(userBO.getName())
        //         || userBO.getGender() == null
        //         || userBO.getAge() == null
        //         || StringUtils.isEmpty(userBO.getTelphone())) {
        //     throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        // }
        ValidationResult result = validator.validate(userBO);
        if (result.isHasError()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, result.getErrMsg());
        }

        // 实现BO->DO的方法
        User user = convertFromUserBO(userBO);
        // 使用insertSelective而不用insert，是因为前者会判断，插入的值是否为空，如果为空，则依赖数据库提供默认值，而不设置null，避免使用null
        try {
            userMapper.insertSelective(user);
        } catch (DuplicateKeyException e) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "该手机号已注册");
        }

        // 将新增的用户id赋值给BO对象，以便于password中的userId一致
        userBO.setId(user.getId());

        UserPassword userPassword = convertPasswordFromUserBO(userBO);
        userPasswordMapper.insertSelective(userPassword);
    }

    @Override
    public UserBO validateLogin(String telphone, String encrptPasswrod) throws BusinessException {
        // 通过用户的手机号获取用户信息
        User user = userMapper.selectByTelphone(telphone);
        if (user == null) {
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }
        UserPassword userPassword = userPasswordMapper.getByUserId(user.getId());
        UserBO userBO = convertFromUser(user, userPassword);

        // 比较用户信息内加密的密码是否和传输进来的密码相同
        if (!StringUtils.equals(encrptPasswrod, userBO.getEncrpt_password())) {
            throw new BusinessException(EmBusinessError.USER_LOGIN_FAIL);
        }

        return userBO;
    }

    // 将UserBO转化为UserPassword
    public UserPassword convertPasswordFromUserBO(UserBO userBO) throws BusinessException {
        if (userBO == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        UserPassword userPassword = new UserPassword();
        userPassword.setEncrptPassword(userBO.getEncrpt_password());
        userPassword.setUserId(userBO.getId());

        return userPassword;
    }

    // 将UserBO转化为User
    public User convertFromUserBO(UserBO userBO) throws BusinessException {
        if (userBO == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userBO,user);
        return user;
    }

    // 将User转化为UserBO
    public UserBO convertFromUser(User user, UserPassword userPassword) {
        if (user == null) {
            return null;
        }
        UserBO userBO = new UserBO();
        BeanUtils.copyProperties(user, userBO);
        // 为业务模型对象设置userPassword
        userBO.setEncrpt_password(userPassword.getEncrptPassword());
        return userBO;
    }
}
